/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.wx.gk.handler;

import cn.ac.iie.di.commons.httpserver.framework.handler.HandlerI;
import cn.ac.iie.di.commons.httpserver.framework.util.ParseRequestStream;
import cn.ac.iie.di.wx.gk.common.RuntimeEnv;
import cn.ac.iie.di.wx.gk.httpService.HttpSender;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Request;

/**
 *
 * @author Administrator
 */
public class CmdAppealHandler implements HandlerI {

    static Logger logger = Logger.getLogger(CmdAppealHandler.class.getName());

    @Override
    public void init() throws Exception {
    }

    @Override
    public void execute(Request pRequest, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //提供指令申诉接口，记录双方指令的发送和接收的内容。
        String appealCmd = ParseRequestStream.parseRequestStreamAsString(pRequest.getInputStream());
        logger.info("appeal cmd is " + appealCmd);
        int count = 0;
        ServletOutputStream out = response.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(out);
        while (true) {
            if (RuntimeEnv.CmdAppealLimit.get() < Integer.parseInt((String) RuntimeEnv.getParam(RuntimeEnv.CmdAppealLimitValue))) {
                RuntimeEnv.CmdAppealLimit.incrementAndGet();
//获取指令响应，根据提交的指令请求，向tx获取指令响应
                HttpSender hs = new HttpSender();
                String responseCmd = hs.closableHttpClient(appealCmd, (String) RuntimeEnv.getParam(RuntimeEnv.appeal));//json的字符串
//                String responseCmd = "{\"statuscode\":0,\"statusinfo\":\"ok\"}";
                logger.info("appeal response cmd is " + responseCmd);
                InputStream inputStream = new ByteArrayInputStream(responseCmd.getBytes("UTF-8"));

                //返回指令结果
                if(responseCmd.equals("")){
                    //连接超时
                    inputStream = new ByteArrayInputStream("{\"statuscode\":-1,\"statusinfo\":\"not ok\"}".getBytes("UTF-8"));
                }
                byte[] bytesContent = new byte[1024 * 2];
                int bytesReadIn = 0;
                while ((bytesReadIn = inputStream.read(bytesContent, 0, 1024 * 2)) > 0) {
                    bos.write(bytesContent, 0, bytesReadIn);
                }
                bos.flush();
                bos.close();
                RuntimeEnv.CmdAppealLimit.decrementAndGet();
                break;
            }
            if (count > 20) {
                //连接数过大
                InputStream inputStream = new ByteArrayInputStream("{\"statuscode\":1,\"statusinfo\":\"ok\"}".getBytes("UTF-8"));

                //返回指令结果
                byte[] bytesContent = new byte[1024 * 2];
                int bytesReadIn = 0;
                while ((bytesReadIn = inputStream.read(bytesContent, 0, 1024 * 2)) > 0) {
                    bos.write(bytesContent, 0, bytesReadIn);
                }
                bos.flush();
                bos.close();
                break;
            }
            ++count;
            Thread.sleep(100);
        }

    }

}
